package com.fh.common.api.vo;

import com.fh.common.constant.CommonConstant;
import com.github.pagehelper.PageInfo;
import lombok.Data;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Qiu,Junda
 * @date 2019年4月3日
 * @description
 */
@Data
public class Result<T> implements Serializable {

	private static final long serialVersionUID = 1L;

	/**
	 * 成功标志
	 */
	private boolean success;

	/**
	 * 返回处理消息
	 */
	private String message="请求成功";

	/**
	 * 返回代码
	 */
	private Integer code;
	
	/**
	 * 返回数据对象 data
	 */
	private T result;

	/**
	 * 时间戳
	 */
	private long timestamp = System.currentTimeMillis();

	public void error500(String message) {
		this.message = message;
		this.code = CommonConstant.SC_INTERNAL_SERVER_ERROR_500;
		this.success = false;
	}

	public void success(String message) {
		this.message = message;
		this.code = CommonConstant.SC_OK_200;
		this.success = true;
	}
	
	public static Result<Object> error(String msg) {
		return error(CommonConstant.SC_INTERNAL_SERVER_ERROR_500, msg);
	}
	
	public static Result<Object> error(int code, String msg) {
		Result<Object> r = new Result<Object>();
		r.setCode(code);
		r.setMessage(msg);
		r.setSuccess(false);
		return r;
	}
	
	public static Result<Object> ok(String msg) {
		Result<Object> r = new Result<Object>();
		r.setSuccess(true);
		r.setCode(CommonConstant.SC_OK_200);
		r.setMessage(msg);
		return r;
	}
	
	public static Result<Object> ok(Object obj) {
		Result<Object> r = new Result<Object>();
		r.setSuccess(true);
		r.setCode(CommonConstant.SC_OK_200);
		r.setResult(obj);
		return r;
	}
	
	public static Result<Object> ok(Object obj, String message){
		Result<Object> r = new Result<Object>();
		r.setSuccess(true);
		r.setCode(CommonConstant.SC_OK_200);
		r.setResult(obj);
		r.setMessage(message);
		return r;
	}
	
	/**
	 * pagehelper分页结果重排
	 */
	public static Result<Object> okPage(List data){
		Result<Object> r = new Result<Object>();
		PageInfo pageInfo = new PageInfo(data);
		Map<String, Object> result = new HashMap<>();
        result.put("size", pageInfo.getPageSize());
        result.put("pages", pageInfo.getPages());
        result.put("total", pageInfo.getTotal());
        result.put("current", pageInfo.getPageNum());
        result.put("records", pageInfo.getList());
        result.put("searchCount", true);
		r.setSuccess(true);
		r.setCode(CommonConstant.SC_OK_200);
		r.setResult(result);
		return r;
	}
}
